package net.adetech.sms.service.impl;

import net.adetech.sms.entity.DcSms;
import net.adetech.sms.service.IDcSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class DcSmsServiceImpl implements IDcSmsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<DcSms> getSmsListByPushState(String pushState) {
        String sql = "select * from hge_ftp.dc_sms where push = ?";
        if ("0".equals(pushState))
        {
            sql = "select * from hge_ftp.dc_sms where push = ? or push is null";
        }
        List<DcSms> dcSmsList = jdbcTemplate.query(sql,new Object[]{pushState},new DcSmsRowMapper());



        return dcSmsList;
    }

    @Override
    public void updatePushState(Long id) {
        final String sql = "update hge_ftp.dc_sms set push = '1' where id = ?";
        jdbcTemplate.update(sql,new Object[]{id});
    }
}

class DcSmsRowMapper implements RowMapper<DcSms>{

    @Override
    public DcSms mapRow(ResultSet rs, int rowNum) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        Set<String> fieldSet = new HashSet<String>();
        for (int i = 1; i <= columnCount; i++) {
            fieldSet.add(rsmd.getColumnName(i));
        }
        DcSms dcSms = new DcSms();
        if (fieldSet.contains("ID") && null != rs.getObject("ID")) {
            dcSms.setId(rs.getLong("ID"));
        }
        if (fieldSet.contains("CONTENT") && null != rs.getObject("CONTENT")) {
            dcSms.setContent(rs.getString("CONTENT"));
        }
        if (fieldSet.contains("PHONE") && null != rs.getObject("PHONE")) {
            dcSms.setPhone(rs.getString("PHONE"));
        }
        if (fieldSet.contains("PUSH") && null != rs.getObject("PUSH")) {
            dcSms.setPush(rs.getString("PUSH"));
        }
        if (fieldSet.contains("SMS_TIME") && null != rs.getObject("SMS_TIME")) {
            dcSms.setSmsTime(rs.getTimestamp("SMS_TIME"));
        }
        return dcSms;
    }
}
